package com.zhku.shoppingspringboot.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.zhku.shoppingspringboot.pojo.entity.*;
import com.zhku.shoppingspringboot.mapper.GoodsMapper;
import com.zhku.shoppingspringboot.pojo.vo.CategoryVO;
import com.zhku.shoppingspringboot.pojo.vo.GoodsVO;
import com.zhku.shoppingspringboot.service.IGoodsService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.query.Query;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author jieeee
 * @since 2025-01-02
 */
@Service
public class GoodsServiceImpl extends ServiceImpl<GoodsMapper, Goods> implements IGoodsService {

    @Autowired
    private SessionFactory sessionFactory; // 注入 SessionFactory

    @Override
    public com.zhku.shoppingspringboot.pojo.entity.goodsData.Goods getOneGoods(Long id) {
        com.zhku.shoppingspringboot.pojo.entity.goodsData.Goods  _goods = new com.zhku.shoppingspringboot.pojo.entity.goodsData.Goods ();

        Session session = sessionFactory.getCurrentSession(); // 获取当前会话
        Goods goods = session.get(Goods.class,id);

        _goods.setId(String.valueOf(id));
        _goods.setName(goods.getName());
        _goods.setSpuCode(goods.getSpuCode());
        _goods.setDesc(goods.getDesc());
        _goods.setPrice(String.valueOf(goods.getPrice()));
        _goods.setOldPrice(String.valueOf(goods.getOldPrice()));
        _goods.setDiscount(Math.round( goods.getDiscount()));
        _goods.setInventory(goods.getInventory());
        _goods.setSalesCount(goods.getSalesCount());
        _goods.setCommentCount(0); // 这个统计评论表
        _goods.setCollectCount(0); // 这个统计用户收藏数量
//        _goods.setMainVideos(convertStringToList(goods.getMainVideos())); // toCheck
        // 将 JSON 字符串转换为 List<String>
        _goods.setMainPictures(convertStringToList(goods.getMainVideos()));
        _goods.setVideoScale(goods.getVideoScale());
        _goods.setMainPictures(convertStringToList(goods.getMainPictures())); // toCheck
        _goods.setPreSale(goods.getIsPreSale());
        _goods.setRecommends(goods.getRecommends());

        // 处理分类数据
        List<String> categoriesIdList = convertStringToList(goods.getCategories());
        List<com.zhku.shoppingspringboot.pojo.entity.goodsData.Categories> _categoriesList= new ArrayList<>();
        for (int i = 0; i < categoriesIdList.size(); i++) {
            Categories categories = session.get(Categories.class, Integer.parseInt(categoriesIdList.get(i)));
            com.zhku.shoppingspringboot.pojo.entity.goodsData.Categories _categories = new com.zhku.shoppingspringboot.pojo.entity.goodsData.Categories();
            _categories.setId(String.valueOf(categories.getId()));
            _categories.setName(categories.getName());
            _categories.setLayer(categories.getLayer());
//添加父分类
            if(categories.getParentId() != 0){
                Categories categoriesParent = session.get(Categories.class, categories.getParentId());
                com.zhku.shoppingspringboot.pojo.entity.goodsData.Parent _parent = new com.zhku.shoppingspringboot.pojo.entity.goodsData.Parent();
                _parent.setId(String.valueOf(categoriesParent.getId()));
                _parent.setName(categoriesParent.getName());
                _parent.setLayer(categoriesParent.getLayer());
                _categories.setParent(_parent);
            }

            _categoriesList.add(_categories);

        }
        _goods.setCategories(_categoriesList);


        // 处理品牌数据
        Brand brand = session.get(Brand.class, goods.getBrandId());
        com.zhku.shoppingspringboot.pojo.entity.goodsData.Brand _brand= new com.zhku.shoppingspringboot.pojo.entity.goodsData.Brand();

        _brand.setId(brand.getId());
        _brand.setName(brand.getName());
        _brand.setDesc(brand.getDesc());
        _brand.setPicture(brand.getPicture());
        _brand.setLogo(brand.getLogo());
        _brand.setNameEn(brand.getNameEn());
        _brand.setPlace(brand.getPlace());
        _brand.setType(brand.getType());
        _goods.setBrand(_brand);


        // 处理商品详情 Hibernate Query Language [HQL]
        com.zhku.shoppingspringboot.pojo.entity.goodsData.Details _details = new com.zhku.shoppingspringboot.pojo.entity.goodsData.Details();
        String hql = "FROM Details d WHERE d.goodsId = :goodsId";
        Query<Details> queryDetailList = session.createQuery(hql, Details.class);
        queryDetailList.setParameter("goodsId", Long.parseLong(_goods.getId()));
        List<Details> detailsList = queryDetailList.list();

        for (Details details : detailsList) {
            if (details.getName().equals("picture")){
                _details.getPictures().add(details.getValue());
            }else{
                com.zhku.shoppingspringboot.pojo.entity.goodsData.Properties _properties = new com.zhku.shoppingspringboot.pojo.entity.goodsData.Properties();
                _properties.setName(details.getName());
                _properties.setValue(details.getValue());
                _details.getProperties().add(_properties);
            }
        }
        _goods.setDetails(_details);


        // 处理商品规格信息 skus
        List< com.zhku.shoppingspringboot.pojo.entity.goodsData.Skus> _skusList = new ArrayList<>();
        List<Long> specesIdList = new ArrayList<>();
        String hql1 = "FROM Skus s WHERE s.goodsId = :goodsId";
        Query<Skus> querySkusList = session.createQuery(hql1, Skus.class);
        querySkusList.setParameter("goodsId", Long.parseLong(_goods.getId()));
        List<Skus> skusList = querySkusList.list();

        for (Skus skus : skusList) {
            com.zhku.shoppingspringboot.pojo.entity.goodsData.Skus _skus = new  com.zhku.shoppingspringboot.pojo.entity.goodsData.Skus();
            _skus.setId(String.valueOf(skus.getId()));
            _skus.setInventory(skus.getInventory());
            _skus.setSkuCode(String.valueOf(skus.getSkuCode()));
            _skus.setPicture(skus.getPicture());
            _skus.setOldPrice(String.valueOf(skus.getOldPrice()));
            _skus.setPrice(String.valueOf(skus.getPrice()));

            List< com.zhku.shoppingspringboot.pojo.entity.goodsData.Specs> _specsList = new ArrayList<>();
            for (String s : convertStringToList(skus.getSpecsIdList())) {
                Specs specs = session.get(Specs.class, Long.parseLong(s));

                com.zhku.shoppingspringboot.pojo.entity.goodsData.Specs _specs = new com.zhku.shoppingspringboot.pojo.entity.goodsData.Specs();
//                _specs.setId(String.valueOf(specs.getId()));
                _specs.setName(specs.getName());
                _specs.setValueName(specs.getSpecsName());
                specesIdList.add(specs.getSpecsId());


                _specsList.add(_specs);
            }

            _skus.setSpecs(_specsList);

            _skusList.add(_skus);

        }
        _goods.setSkus(_skusList);


        // 处理商品规格信息 Specs
        // 数据去重
        List<Long> uniqueSpecsIdList = specesIdList.stream()
                .distinct()
                .collect(Collectors.toList());

        List<com.zhku.shoppingspringboot.pojo.entity.goodsData.Specs> _specsList = new ArrayList<>();
        for (Long specsId : uniqueSpecsIdList) {
            com.zhku.shoppingspringboot.pojo.entity.goodsData.Specs _specs = new com.zhku.shoppingspringboot.pojo.entity.goodsData.Specs();
//            List<Long> specesIdList = new ArrayList<>();
            String hql2 = "FROM Specs s WHERE s.specsId = :specsId";
            Query<Specs> querySpecsList = session.createQuery(hql2, Specs.class);
            querySpecsList.setParameter("specsId", specsId);
            List<Specs> specsList = querySpecsList.list();
            _specs.setId(specsId.toString());
// value
            List<com.zhku.shoppingspringboot.pojo.entity.goodsData.Values> _valuesList = new ArrayList<>();
            for (Specs specs : specsList) {
                com.zhku.shoppingspringboot.pojo.entity.goodsData.Values _values = new com.zhku.shoppingspringboot.pojo.entity.goodsData.Values();
                _specs.setName(specs.getName()); // 这个值只能从这里拿了
                _values.setName(specs.getSpecsName());
                _values.setDesc(specs.getSpecsDesc());
                _values.setDesc(specs.getSpecsPicture());

                _valuesList.add(_values);
            }
            _specs.setValues(_valuesList);
            _specsList.add(_specs);
        }
        _goods.setSpecs(_specsList);
        return _goods;
    }


    // 字符串转List<String>
    public static List<String> convertStringToList(String input) {
        List<String> resultList = new ArrayList<>();

        // 检查输入是否为空
        if (input == null || input.isEmpty()) {
            return resultList; // 返回空列表
        }

        // 去掉方括号
        input = input.trim();
        if (input.startsWith("[") && input.endsWith("]")) {
            input = input.substring(1, input.length() - 1);
        }

        // 按逗号分割字符串
        String[] stringArray = input.split(",");

        // 去除每个元素的空格并添加到列表中
        for (String str : stringArray) {
            resultList.add(str.trim()); // 去除空格并添加到列表
        }

        return resultList;
    }
    @Override
    public List<GoodsVO> getGoodsByCategoryId(Integer categoryId) {
        LambdaQueryWrapper<Goods> lambdaQueryWrapper=new LambdaQueryWrapper<Goods>()
                .like(Goods::getCategories,categoryId+"")
                .select(Goods::getId,
                        Goods::getName,
                        Goods::getDesc,
                        Goods::getPrice,
                        Goods::getDiscount,
                        Goods::getSalesCount,
                        Goods::getMainPictures);
        List<Goods> list = this.list(lambdaQueryWrapper);
        List<GoodsVO> collect = list.stream().map(item -> new GoodsVO().setId(String.valueOf(item.getId()))
                .setName(item.getName())
                .setDesc(item.getDesc())
                .setPrice(String.valueOf(item.getPrice()))
                .setPicture(item.getMainPictures().replace("[", "").split(",")[0])
                .setDiscount(Math.round(item.getDiscount()))
                .setOrderNum(item.getSalesCount())).collect(Collectors.toList());
        return collect;
    }

    @Override
    public List<GoodsVO> searchAll(String keyword) {

        LambdaQueryWrapper<Goods> lambdaQueryWrapper=new LambdaQueryWrapper<Goods>()
                .like(Goods::getName,keyword)
                .select(Goods::getId,
                        Goods::getName,
                        Goods::getDesc,
                        Goods::getPrice,
                        Goods::getDiscount,
                        Goods::getSalesCount,
                        Goods::getMainPictures);
        List<Goods> list = this.list(lambdaQueryWrapper);
        List<GoodsVO> collect = list.stream().map(item -> new GoodsVO().setId(String.valueOf(item.getId()))
                .setName(item.getName())
                .setDesc(item.getDesc())
                .setPrice(String.valueOf(item.getPrice()))
                .setPicture(item.getMainPictures().replace("[", "").split(",")[0])
                .setDiscount(Math.round(item.getDiscount()))
                .setOrderNum(item.getSalesCount())).collect(Collectors.toList());
        return collect;
    }



}
